package com.example.aspect;

import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Sheeper
 * @date 2018/5/23.
 */
@Aspect
@Configuration
@Order(2)
public class PageOrderAspect {

    public final static String PAGE = "page";
    public final static String PAGE_NUM = "pageNum";
    public final static String ORDER_KEY = "orderKey";
    public final static String ORDER_MODEL = "orderModel";
    public final static String PRIMARY_KEY = "primaryKey";
    public final static Pattern pattern = Pattern.compile("^\\w+$");

    @Pointcut("execution(* com.example.service..*.list*(..))")
    public void pageOrder() {
    }

    @Around("pageOrder()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] objects = joinPoint.getArgs();
        if (objects.length == 1 && objects[0] instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) objects[0];
            if (params.containsKey(PAGE) && params.containsKey(PAGE_NUM)) {
                try {
                    PageHelper.startPage(Integer.parseInt(params.get(PAGE).toString())
                            , Integer.parseInt(params.get(PAGE_NUM).toString()));
                } catch (Exception e) {
                    //throw new ValidateException("com_page_parameters_error");
                }
            } else {
              //  throw new ValidateException("com_page_empty");
            }

            if (params.containsKey(ORDER_KEY) && !StringUtils.isEmpty(params.get(ORDER_KEY))
                    && params.containsKey(ORDER_MODEL) && !StringUtils.isEmpty(params.get(ORDER_MODEL))) {

                if (!pattern.matcher(String.valueOf(params.get(ORDER_KEY))).matches()) {
                   // throw new BusinessLogicException("request_param_error");
                }

                if (!pattern.matcher(String.valueOf(params.get(ORDER_MODEL))).matches()) {
                   // throw new BusinessLogicException("request_param_error");
                }

                String orderBy = params.get(ORDER_KEY) + " " + params.get(ORDER_MODEL);
                if (params.containsKey(PRIMARY_KEY)) {
                    orderBy = orderBy + ", " + params.get(PRIMARY_KEY);
                }
                PageHelper.orderBy(orderBy);
            }
        }
        return joinPoint.proceed();
    }
}
